from arbre import Context, activate

def printFluc(defc, callc, executionPoint):
  code=executionPoint.resolve(['code'])

  tokenTree=tokenizeFlucCode(defc, code)
#  print 'tokenTree:', tokenTree
#  print 'ltt:', len(tokenTree)
  return printTokenTree(tokenTree, '')
  
def tokenizeFlucCode(defc, code):
  tokenType=code[0]
  tokenValue=code[1]
    
  if tokenType!='func':
    print 'Error! Code not func!'
    return
      
  sym=tokenValue[0]
  args=tokenValue[1]
    
  #print 'sym:', sym
  #print 'args:', args
    
  view=defc.resolve(sym+".view")
  #print 'view:', view
  return applyView(defc, view, args)
    
def printTokenTree(tokenTree, prefix):
  #print 'ptt-len:', len(tokenTree)
  #print 'printTokenTree', tokenTree, '_'+prefix+'_'
  s=prefix
  head=tokenTree[0]
  tail=tokenTree[1]
  
  #print 'ptt-head:', head
  #print 'ptt-tail:', tail
    
  for token in head:
    #print 'token:', token
    tokenType=token[0]
    tokenValue=token[1]
    if tokenType=='literal' and type(tokenValue)==str:
      s=s+"'"+str(tokenValue)+"'"
    else:
      s=s+str(tokenValue)
      
  if len(tail)>0:
    s=s+"\n"
    
    for child in tail:
      if len(child)>0:
        s=s+printTokenTree(child, prefix+'  ')
        if s[-1]!="\n":
          s=s+"\n"
    
  return s
  
def applyView(defc, view, args):
  #print 'applyView:', view, args
  head=[]
  tail=[]
  
  for viewToken in view:
    #print 'viewToken:', viewToken
    tokenType=viewToken[0]
    tokenValue=viewToken[1]
    
    if tokenType=='symref':
      value=args[tokenValue]
      valueType=value[0]
      if valueType=='func':
        func=value[1]
        sym=func[0]
        funcArgs=func[1]
        subView=defc.resolve(sym+".view")
        #print 'subView:', sym, subView
        subTokens=applyView(defc, subView, funcArgs)
        #print 'subTokens:', subTokens
        subHead=subTokens[0]
        subTail=subTokens[1]
        for subToken in subHead:
          head.append(subToken)
        if len(subTail)>0:
          print 'Error! Subtail!', subTail
      else:
        head.append(value)
    elif tokenType=='func':
      head.append(viewToken)
    elif tokenType=='whitespace':
      head.append(viewToken)
    elif tokenType=='sugar':
      head.append(viewToken)
    elif tokenType=='block':
      value=args[tokenValue]
      valueType=value[0]
      if valueType=='func':
        func=value[1]
        sym=func[0]
        funcArgs=func[1]
        subView=defc.resolve(sym+".view")
        #print 'subView:', sym, subView
        tail.append(applyView(defc, subView, funcArgs))
      elif valueType=='literal':
        tail.append([[value], []])
      else:
        print 'Error! Subtail for tail is not func!', subTail
    else:
      print 'Unknown token type!', tokenType
      
  #print 'apply head', head
  #print 'apply tail', tail
  
  #print 'ahl:', len(head)
  #print 'atl:', len(tail)
      
  return [head, tail]    